package com.robot.merchant.controller;

import com.robot.merchant.client.SmsClient;
import com.robot.merchant.pojo.Store;
import com.robot.merchant.service.StoreService;
import entity.Result;
import entity.Sms;
import entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.JwtUtil;

import java.util.HashMap;

/**
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/store")
public class LoginController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CheckUtil checkUtil;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private StoreService storeService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 手机状态码注册登录
     *
     * @param checkCode
     * @param store
     * @return
     */
    @RequestMapping(value = "/login/phone/{checkCode}",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result registerPhone(@PathVariable String checkCode, @RequestBody Store store) {
        //判断手机号是否合法
        String phone = store.getPhone();
        logger.info("login phone=" + phone + ", checkCode=" + checkCode);
        if (!checkUtil.checkPhone(phone)) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        //判断验证码
        checkCode = checkCode.trim();
        if ("".equals(checkCode)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE);
        }
        Sms sms = new Sms("merchant", phone, "login");
        if (!smsClient.isCheckCodeExpire(sms)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE_EXPIRED);
        }
        if (!smsClient.isCorrectCheckCode(sms, checkCode)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE);
        }

        //检查商家
        Store storeInDb = storeService.findByPhone(phone);
        String message = storeService.checkStore(storeInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("token", jwtUtil.createJwt(storeInDb.getId(), storeInDb.getPhone(), "merchant"));
        map.put("role", "merchant");
        //按理应该是storeId,但前端已经用memberId了,所以这里不改了
        map.put("memberId", storeInDb.getId());
        //删除redis里面的验证码
        smsClient.deleteCheckCode(sms);
        return new Result(StatusCode.SUCCESS_LOGIN, map);
    }

    /**
     * 手机号密码登录
     *
     * @param store
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result passwordLogin(@RequestBody Store store) {
        //判断手机号是否合法
        logger.info("store=" + store);
        String phone = store.getPhone();
        if (!checkUtil.checkPhone(phone)) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }

        if (store.getPassword() == null || "".equals(store.getPassword())) {
            return new Result(StatusCode.ERROR_PASSWORD_REQUIRED);
        }

        //检查商家
        Store storeInDb = storeService.findByPhone(phone);
        String message = storeService.checkStore(storeInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        if (!encoder.matches(store.getPassword(), storeInDb.getPassword())) {
            return new Result(StatusCode.ERROR_PASSWORD_WRONG);
        }

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("token", jwtUtil.createJwt(storeInDb.getId(), storeInDb.getPhone(), "merchant"));
        map.put("role", "merchant");
        //按理应该是storeId,但前端已经用memberId了,所以这里不改了
        map.put("memberId", storeInDb.getId());
        return new Result(StatusCode.SUCCESS_LOGIN, map);
    }

}
